<template>
    <div>
        <el-card style="padding: 20px">
            <el-form ref="searchForm" :inline="true" :model="searchInfo">
                <el-form-item label="编号">
                    <el-input v-model="searchInfo.Token" placeholder="编号" />
                </el-form-item>
                <el-form-item label="名字">
                    <el-input v-model="searchInfo.Name" placeholder="名字" />
                </el-form-item>
                <el-form-item label="公司">
                    <SearchObjectSelect v-model="searchInfo.TokenOfCompany" :fetchDataFunc="fetchCompanyList()"
                        :getKey="it => it.Token" :getDesc="it => it.Name" />
                </el-form-item>
                <el-form-item label="工序">
                    <SearchObjectSelect v-model="searchInfo.TokenOfProcess" :fetchDataFunc="fetchProcessList()"
                        :getKey="it => it.Token" :getDesc="it => it.Name" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card style="margin-top: 20px; padding: 20px">
            <div class="gva-btn-list">
                <el-button type="primary" @click="openDialog('add')">新增</el-button>
                <el-popover v-model:visible="deleteVisible" placement="top" width="160">
                    <p>确定要删除吗？</p>
                    <div style="text-align: right; margin-top: 8px">
                        <el-button size="small" class="primary-button" @click="onDelete">确定</el-button>
                        <el-button size="small" class="common-button" @click="deleteVisible = false">取消</el-button>
                    </div>
                    <template #reference>
                        <el-button type="primary" :disabled="!objs.length" style="margin-left: 10px"
                            @click="deleteVisible = true">删除</el-button>
                    </template>
                </el-popover>
                <el-button @click="onSubmit">刷新</el-button>
            </div>
            <el-table border :scrollbar-always-on="true" :style="{ 'border-bottom': '1px solid #ebeef5' }"
                :header-cell-style="{
                    'border-bottom': '1px solid #ebeef5',
                    'background-color': '#f5f8fc'
                }" max-height="519px" :data="tableData" @sort-change="onSortChange"
                @selection-change="onSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column v-for="item in listFields" :label="item.title" align="center" :prop="item.key"
                    :key="item.key" :sortable="item.sorter ? 'custom' : false" :width="item.width ? item.width : 'auto'">
                    <template #default="scope">
                        <data-table-item :itemRender="item.render" :itemData="scope.row[item.dataIndex]" />
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作" width="260">
                    <template #default="scope">
                        <div>
                            <el-button icon="edit" size="small" class="common-button"
                                @click="editObject(scope.row)">编辑</el-button>
                            <el-button icon="delete" size="small" class="del-button"
                                @click="deleteObject(scope.row)">删除</el-button>

                            <el-button class="common-button" size="small" icon="ArrowDown">
                                <el-dropdown @command="handleCommand($event, scope.row)">
                                    <span class="el-dropdown-link">
                                        其他
                                        <!-- <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon> -->
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item command="behave">举措管理</el-dropdown-item>
                                            <el-dropdown-item command="target">指标管理</el-dropdown-item>
                                            <el-dropdown-item command="benefitlog">爬坡目标管理</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination :current-page="page" :page-size="pageSize" :page-sizes="[10, 30, 50, 100]" :total="total"
                    layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange"
                    @size-change="handleSizeChange" />
            </div>
        </el-card>
        <el-drawer v-model="dialogFormVisible" :before-close="closeDialog" :title="dialogTitle" center>
            <el-form ref="objForm" :model="objInfo" :rules="rules" label-position="left" label-width="25%"
                style="margin: 0 30px">
                <el-form-item label="编号" prop="Token" placeholder="请输入编号">
                    <el-input v-model="objInfo.Token"></el-input>
                </el-form-item>
                <el-form-item label="名字" prop="Name" placeholder="请输入名字">
                    <el-input v-model="objInfo.Name"></el-input>
                </el-form-item>
                <el-form-item label="公司" prop="Company">
                    <SelectOneContainer :model="CompanyObj" v-model="objInfo.TokenOfCompany" />
                </el-form-item>
                <el-form-item label="牵头部门" prop="Department">
                    <SelectOneContainer :model="DepartmentObj" v-model="objInfo.TokenOfDepartment" />
                </el-form-item>
                <el-form-item label="辅助部门" prop="AuxiliaryDepartmentList">
                    <SelectOneContainer :model="DepartmentObj" v-model="objInfo.AuxiliaryDepartmentList" :multiple="true" />
                </el-form-item>
                <el-form-item label="工序" prop="Process">
                    <SelectOneContainer :model="ProcessObj" v-model="objInfo.TokenOfProcess" />
                </el-form-item>
                <el-form-item label="当前收益" prop="CurrentIncome" placeholder="请输入当前收益">
                    <el-input v-model="objInfo.CurrentIncome"></el-input>
                </el-form-item>
                <el-form-item label="目标收益" prop="TargetIncome" placeholder="请输入目标收益">
                    <el-input v-model="objInfo.TargetIncome"></el-input>
                </el-form-item>
                <el-form-item label="吨刚效益" prop="IncomePerTon" placeholder="请输入吨刚效益">
                    <el-input v-model="objInfo.IncomePerTon"></el-input>
                </el-form-item>
                <el-form-item label="负责人" prop="Responsible" placeholder="请输入负责人">
                    <el-input v-model="objInfo.Responsible"></el-input>
                </el-form-item>
                <el-form-item label="收益描述" prop="IncomeDescription" placeholder="请输入收益描述">
                    <el-input v-model="objInfo.IncomeDescription"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="enterDialog">确 定</el-button>
                <el-button @click="closeDialog">取 消</el-button>
            </template>
        </el-drawer>

    </div>
</template>
<script setup>
import SelectOneContainer from "@/loc/components/SelectOneContainer.vue";
import SearchObjectSelect from "@/loc/components/SearchObjectSelect.vue";
import DataTableItem from "@/loc/components/DataTableItem.vue";
import { ref } from "vue";
import { convertString } from "@/loc/utils/valueTools.js";
import { ElMessage, ElMessageBox } from "element-plus";

import { useRouter } from "vue-router";


import { createObjectListBinding } from "@/loc/utils/dataBindingHelper";
import Company from "@/loc/pages/company/model";
import Department from "@/loc/pages/department/model";
import Process from "@/loc/pages/process/model";
import Obj from "./model";
const router = useRouter();

const obj = new Obj();
const objs = ref([]);
const type = ref("");
const CompanyObj = new Company();
const ProcessObj = new Process();
const DepartmentObj = new Department();
const rules = ref({
    Token: [
        {
            required: true,
            message: "请填写编号 ",
            trigger: "blur"
        }
    ],
    Name: [
        {
            required: false,
            message: "请填写名字 ",
            trigger: "blur"
        }
    ],
    Company: [
        {
            required: false,
            message: "请填写公司 ",
            trigger: "blur"
        }
    ],
    Process: [
        {
            required: false,
            message: "请填写工序 ",
            trigger: "blur"
        }
    ],
    Department: [
        {
            required: false,
            message: "请填写牵头部门 ",
            trigger: "blur"
        }
    ],
    BehaveProgress: [
        {
            required: false,
            message: "请填写举措进度 ",
            trigger: "blur"
        }
    ],
    CurrentIncome: [
        {
            required: false,
            message: "请填写当前收益 ",
            trigger: "blur"
        }
    ],
    TargetIncome: [
        {
            required: false,
            message: "请填写目标收益 ",
            trigger: "blur"
        }
    ],
    Responsible: [
        {
            required: false,
            message: "请填写负责人 ",
            trigger: "blur"
        }
    ]
});


const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const searchInfo = ref({});
const orderInfo = ref({});
const objForm = ref(null);
const objInfo = ref({
    Token: null,
    Name: null,
    Company: null,
    Process: null,
    Department: null,
    IncomeDescription: null,
    BehaveProgress: null,
    CalculateUtc: null,
    IncomePerTon: null,
    CurrentIncome: null,
    TargetIncome: null,
    Responsible: null,
    IncomePerTon: 0
});
const onReset = () => {
    searchInfo.value = {};
    orderInfo.value = {};
};

// 搜索
const onSubmit = () => {
    page.value = 1;
    pageSize.value = 10;
    getTableData(true);
};

// 分页
const handleSizeChange = val => {
    pageSize.value = val;
    getTableData(true);
};

//改变当前页
const handleCurrentChange = val => {
    page.value = val;
    getTableData(false);
};

// 排序
const onSortChange = ({ prop, order }) => {
    if (prop) {
        orderInfo.value.OrderKey = prop;
        orderInfo.value.Desc = order === "descending";
    }
    getTableData(false);
};

// 查询
// getTotalSize - 是否重新获取总尺寸
const getTableData = getTotalSize => {
    if (getTotalSize) {
        //如果要重新获取总页数,则拉取总页数
        obj.count4Page({ ...convertString(searchInfo.value) }).then(count => {
            if (count.code === 0) {
                total.value = count.count;
                //计算最大的页码,页码从1开始
                const maxPage = total.value / pageSize.value + 1;
                if (page.value > maxPage) {
                    page.value = maxPage;
                }
            }
        });
    }
    obj
        .pageObj({
            PageInfo: { Page: page.value, PageSize: pageSize.value },
            OrderInfo: { ...orderInfo.value },
            SearchInfo: { ...convertString(searchInfo.value) }
        })
        .then(table => {
            if (table.code === 0) {
                tableData.value = table.list;
            }
        });
};

getTableData(true);
const listFields = obj.fields.filter(item => !item.hide);

// 批量操作
const onSelectionChange = val => {
    objs.value = val;
};

const deleteVisible = ref(false);
const onDelete = () => {
    const ids = objs.value.map(item => obj.getKey(item));
    obj.deleteObjs({ ids }).then(res => {
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: res.msg
            });
            if (tableData.value.length === ids.length && page.value > 1) {
                page.value--;
            }
            deleteVisible.value = false;
            getTableData(true);
        }
    });
};

const initForm = () => {
    objForm.value.resetFields();
    objInfo.value = {
        Token: null,
        Name: null,
        Company: null,
        Process: null,
        Department: null,
        IncomeDescription: null,
        BehaveProgress: null,
        CalculateUtc: null,
        IncomePerTon: null,
        CurrentIncome: null,
        TargetIncome: null,
        Responsible: null,
        IncomePerTon: 0
    };
};

const dialogTitle = ref("新增项目");
const dialogFormVisible = ref(false);
const updateOrCreate = ref(true);
const openDialog = key => {
    switch (key) {
        case "add":
            dialogTitle.value = "新增项目";
            updateOrCreate.value = true;
            break;
        case "edit":
            dialogTitle.value = "编辑项目";
            updateOrCreate.value = false;
            break;
        default:
            break;
    }
    type.value = key;
    dialogFormVisible.value = true;
};
const closeDialog = () => {
    initForm();
    dialogFormVisible.value = false;
};

const editObject = row => {
    obj.getObjById({ ID: obj.getKey(row) }).then(res => {
        if (res.code === 0) {
            obj.format4Select(res.value);
            objInfo.value = res.value;
            openDialog("edit");
        }
    });
};

const enterDialog = () => {
    objForm.value.validate(valid => {
        if (valid) {
            switch (type.value) {
                case "add":
                    {
                        obj.createObj(objInfo.value).then(res => {
                            if (res.code === 0) {
                                ElMessage({
                                    type: "success",
                                    message: "添加成功",
                                    showClose: true
                                });
                            }
                            getTableData(true);
                            closeDialog();
                        });
                    }
                    break;
                case "edit":
                    {
                        obj.updateObj(objInfo.value).then(res => {
                            if (res.code === 0) {
                                ElMessage({
                                    type: "success",
                                    message: "编辑成功",
                                    showClose: true
                                });
                            }
                            getTableData(false);
                            closeDialog();
                        });
                    }
                    break;
                default:
                    // eslint-disable-next-line no-lone-blocks
                    {
                        ElMessage({
                            type: "error",
                            message: "未知操作",
                            showClose: true
                        });
                    }
                    break;
            }
        }
    });
};

const deleteObject = row => {
    ElMessageBox.confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    }).then(() => {
        obj.deleteObj(row).then(res => {
            if (res.code === 0) {
                ElMessage({
                    type: "success",
                    message: "删除成功!"
                });
                if (tableData.value.length === 1 && page.value > 1) {
                    page.value--;
                }
                getTableData(true);
            }
        });
    });
};

function fetchCompanyList() {
    return createObjectListBinding(CompanyObj.listObj, {});
}
function fetchProcessList() {
    return createObjectListBinding(ProcessObj.listObj, {});
}
function fetchDepartmentList() {
    return createObjectListBinding(DepartmentObj.listObj, {});
}

function handleCommand(command, row) {
    if (command == "behave") {
        toLinkBehave(row)
    } else if (command == "target") {
        toLinkTarget(row)
    } else if (command == "benefitlog") {
    }
}

//跳转到举措管理，将项目传递过去
function toLinkBehave(row) {
    router.push({ path: "/behaveList", query: { id: row.Token } });
}

//跳转到指标管理，将项目传递过去
function toLinkTarget(row) {
    router.push({ path: "/target", query: { id: row.Token } });
}

</script>
<style scoped>
.gva-btn-list {
    margin-bottom: 10px;
}

.gva-pagination {
    margin-top: 10px;
}
</style>